package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    
    @Autowired
    private OrdersMapper ordersMapper;
    
//    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "* * * * * ?")
    public void processTimeOutOrder(){
        log.info("处理超时配置付的订单,{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //1. 查询所有未支付且超时的订单  select * from orders where status = ? and create_time < time
        List<Orders> list =  ordersMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        
        //2. 判断是否查询到了数据
        if(null != list && list.size() > 0){
            //3. 修改每一个订单的状态和取消的原有和时间 最终更新到数据
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时 系统自动取消");
                orders.setCancelTime(LocalDateTime.now());

                ordersMapper.update(orders);
            }
        }

    }

//    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "* * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理配送中的订单,{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> list = ordersMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if(null != list && list.size() > 0){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);

                ordersMapper.update(orders);
            }
        }

    }
}
